#include "hcsr04.h"
#include "ic.h"
#include "delay.h"
#include "stdio.h"

void hcsr04_init(void)
{
    RCC_INIT_HCSR04_TRIG();
    RCC_INIT_HCSR04_ECHO();
    GPIO_InitTypeDef hcsr04_init = {0};
    
    hcsr04_init.Pin = PIN_HCSR04_TRIG;
    hcsr04_init.Mode = GPIO_MODE_OUTPUT_PP;
    hcsr04_init.Pull = GPIO_PULLDOWN;
    hcsr04_init.Speed = GPIO_SPEED_FREQ_HIGH;
    
    HAL_GPIO_Init(GPIO_HCSR04_TRIG, &hcsr04_init);
    
    hcsr04_init.Pin = PIN_HCSR04_ECHO;
    hcsr04_init.Mode = GPIO_MODE_INPUT;
    hcsr04_init.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIO_HCSR04_ECHO, &hcsr04_init);
}

uint32_t hcsr04_disp_get(void)
{
    uint32_t total_time_us = 0;
    uint32_t total_disp_mm = 0;
    
    HCSR04_TRIG(1);
    delay_us(20);
    HCSR04_TRIG(0);
    
    while (1)
    {
        total_time_us = ic_total_time_get();
//        printf("123");
        if (total_time_us == 0) continue;
        break;
        delay_ms(100);
    }
    
    total_disp_mm = total_time_us * 343.0 / 2000.0;
    printf("total_disp: %d mm\r\n", total_disp_mm);
    return total_disp_mm;
}



